import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_vant_kit/widgets/price.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shoes_shop/api/api.dart';
import 'package:date_format/date_format.dart';
import 'dart:math' as math;

import 'package:shoes_shop/core/utils.dart';

class OrderPage extends StatefulWidget {
  final int index;
  const OrderPage({Key key, this.index = 0}) : super(key: key);

  @override
  _OrderPageState createState() => _OrderPageState();
}

class _OrderPageState extends State<OrderPage>
    with SingleTickerProviderStateMixin {
  TabController _tabController; // Tab Controller 控制器
  List tabs = ["待付款", "待发货", "待收货", "待评价", "售后"];
  Map goodsListObj = {};
  @override
  void initState() {
    super.initState();
    for (int i = 0; i < tabs.length; i++) {
      goodsListObj[i] = {
        'orderList': [],
        'refreshController': new RefreshController(),
        'pageNo': 1,
      };
    }
    // 创建Controller
    _tabController = TabController(
        initialIndex: widget.index, length: tabs.length, vsync: this);
    _tabController.addListener(() {
      // 页面滑动切换
      if (!_tabController.indexIsChanging &&
          (_tabController.index != _tabController.previousIndex)) {
        goodsListObj[_tabController.index]['pageNo'] = 1;
        goodsListObj[_tabController.index]['orderList'] = [];
        EasyLoading.show();
        _getOrderList();

        // getOrder(_tabController.index, 1, 10).then((res) {
        //   setState(() {
        //     goodsListObj[_tabController.index]['orderList'] = res['data'];
        //     goodsListObj[_tabController.index]['pageNo'] = 1;
        //   });
        // });
      }
    });
    EasyLoading.show();
    _getOrderList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('订单中心'),
        bottom: TabBar(
          controller: _tabController,
          tabs: tabs.map((e) => Tab(text: e)).toList(),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: tabs
            .asMap()
            .map((index, item) {
              return MapEntry(
                index,
                SmartRefresher(
                  onRefresh: () {
                    logger.i('刷新');
                    goodsListObj[_tabController.index]['pageNo'] = 1;
                    goodsListObj[_tabController.index]['orderList'] = [];
                    _getOrderList();
                  },
                  onLoading: () {
                    logger.i('加载');
                    _getOrderList();
                  },
                  enablePullUp: true,
                  footer: CustomFooter(
                    builder: (BuildContext context, LoadStatus mode) {
                      Widget body;
                      if (mode == LoadStatus.idle) {
                        //闲置状态
                        body = Text("上拉加载更多");
                      } else if (mode == LoadStatus.loading) {
                        //加载状态
                        body = Text("加载中...");
                      } else if (mode == LoadStatus.failed) {
                        //加载数据失败
                        body = Text("加载失败，稍后重试");
                      } else {
                        //没有数据
                        body = Text("没有更多数据了");
                      }
                      return Container(
                        height: 55.0,
                        child: Center(child: body),
                      );
                    },
                  ),
                  controller: goodsListObj[index]['refreshController'],
                  child: goodsListObj[index]['orderList'].length==0? Center(child: Image.asset('assets/empty@2x.png',width: 300.w,),) : ListView.builder(
                    itemCount: goodsListObj[index]['orderList'].length,
                    scrollDirection: Axis.vertical,
                    physics: BouncingScrollPhysics(),
                    padding: EdgeInsets.fromLTRB(30.w, 40.w, 30.w, 0),
                    itemBuilder: (context, index1) {
                      return Padding(
                        padding: EdgeInsets.only(bottom: 40.w),
                        child: Container(
                          padding: EdgeInsets.fromLTRB(40.w, 30.w, 40.w, 40.w),
                          width: 680.w,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    '订单号:${goodsListObj[index]['orderList'][index1]['No']}',
                                    style: TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold),
                                  ),
                                  Text(
                                    tabs[goodsListObj[index]['orderList']
                                        [index1]['status']],
                                    style: TextStyle(
                                      color: Colors.blue,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ],
                              ),
                              SizedBox(
                                height: 10.w,
                              ),
                              Container(
                                padding: EdgeInsets.fromLTRB(0, 5.w, 0, 15.w),
                                decoration: BoxDecoration(
                                  border: Border(
                                    top: BorderSide(
                                        width: 1, color: Colors.black12),
                                    bottom: BorderSide(
                                        width: 1, color: Colors.black12),
                                  ),
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      '下单时间:${formatDate(DateTime.fromMillisecondsSinceEpoch(goodsListObj[index]['orderList'][index1]['_createTime']), [
                                            yyyy,
                                            '-',
                                            mm,
                                            '-',
                                            dd,
                                            ' ',
                                            HH,
                                            ':',
                                            nn,
                                            ':',
                                            ss
                                          ])}',
                                      style: TextStyle(
                                          fontSize: 14, color: Colors.black54),
                                    ),
                                    SizedBox(
                                      height: 10.w,
                                    ),
                                    ListView.builder(
                                        shrinkWrap:
                                            true, //为true可以解决子控件必须设置高度的问题
                                        physics:
                                            NeverScrollableScrollPhysics(), //禁用滑动事件
                                        itemCount: goodsListObj[index]
                                                    ['orderList'][index1]
                                                ['goods_list']
                                            .length,
                                        itemBuilder: (context, index2) {
                                          return Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              Transform.rotate(
                                                angle: -math.pi / 7,
                                                child: Image.network(
                                                  goodsListObj[index]['orderList']
                                                                  [index1]
                                                              ['goods_list']
                                                          [index2]['shoes_info']
                                                      [0]['imgs'][0],
                                                  width: 150.w,
                                                  height: 150.w,
                                                ),
                                              ),
                                              SizedBox(
                                                width: 20.w,
                                              ),
                                              Expanded(
                                                child: Container(
                                                  height: 150.w,
                                                  child: Column(
                                                    crossAxisAlignment:
                                                        CrossAxisAlignment
                                                            .start,
                                                    mainAxisAlignment:
                                                        MainAxisAlignment
                                                            .spaceBetween,
                                                    children: [
                                                      Text(goodsListObj[index][
                                                                          'orderList']
                                                                      [index1]
                                                                  ['goods_list']
                                                              [
                                                              index2]['shoes_info']
                                                          [0]['title']),
                                                      Row(
                                                        mainAxisAlignment:
                                                            MainAxisAlignment
                                                                .spaceBetween,
                                                        children: [
                                                          Price(
                                                            size: 30.w,
                                                            value: goodsListObj[index]
                                                                            [
                                                                            'orderList']
                                                                        [index1]
                                                                    [
                                                                    'goods_list'][index2]
                                                                [
                                                                'shoes_info'][0]['price'],
                                                          ),
                                                          Text(
                                                              'x${goodsListObj[index]['orderList'][index1]['goods_list'][index2]['count']}'),
                                                        ],
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              ),
                                            ],
                                          );
                                        }),
                                  ],
                                ),
                              ),
                              SizedBox(
                                height: 10.w,
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text('总价:'),
                                  Expanded(
                                    child: Price(
                                      size: 30.w,
                                      value: _settlement(
                                        goodsListObj[index]['orderList'][index1]
                                            ['goods_list'],
                                      ),
                                    ),
                                  ),
                                  Text('查看详情')
                                ],
                              ),
                            ],
                          ),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(20),
                            boxShadow: [
                              BoxShadow(
                                  color: Colors.black12,
                                  offset: Offset(0.0, 5.0), //阴影xy轴偏移量
                                  blurRadius: 10.0, //阴影模糊程度
                                  spreadRadius: 1.0 //阴影扩散程度
                                  ),
                            ],
                            color: Colors.white,
                          ),
                        ),
                      );
                    },
                  ),
                ),
              );
            })
            .values
            .toList(),
      ),
    );
  }

// 获取订单列表
  _getOrderList() async {
    int _index = _tabController.index;
    int _pageNo = goodsListObj[_tabController.index]['pageNo'];
    int _limit = 10;
    await getOrder(_index, _pageNo, _limit).then((res) {
      EasyLoading.dismiss();
      if (res['data'].length == 0) {
        goodsListObj[_index]['refreshController'].loadComplete();
      } else {
        goodsListObj[_index]['pageNo']++;
        setState(() {
          goodsListObj[_index]['orderList']..addAll(res['data']);
        });
      }
      goodsListObj[_index]['refreshController'].refreshCompleted();
    });
  }
}

// 计算价格
_settlement(list) {
  double total = 0;
  for (int i = 0; i < list.length; i++) {
    int count = list[i]['count'];
    double price = list[i]['shoes_info'][0]['price'];
    total = total + (count * price);
  }
  return total;
}
